package com.ahora.org.controller.biometrico.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ahora.org.ejb.dao.util.ConexionBD;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Servlet implementation class DemoServlet
 */
@WebServlet("/ServletDocumentosExpediente")
public class ServletDocumentosExpedienteDB extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {
		if(request.getParameter("codUsu")==null || request.getParameter("idExp")==null || 
			request.getParameter("tipoChar")==null || request.getParameter("codAdj")==null ||
			request.getParameter("idExp").isEmpty() || request.getParameter("codUsu").isEmpty()
			|| request.getParameter("tipoChar").isEmpty()){
			return;
		}
		
		String codUsu = request.getParameter("codUsu");
		String tipoChar = request.getParameter("tipoChar");
		String codAdj = request.getParameter("codAdj");
		int idExp = Integer.parseInt(request.getParameter("idExp"));
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		byte[] archivo = null;
		ServletOutputStream out = response.getOutputStream();
		try {
			con = ConexionBD.getConnection();
			stmt = con.createStatement();
			
			if(tipoChar.equals("r")){
				rs = stmt.executeQuery("select d.documentoscaneado from tb_detalle_cupex_requisito d where d.id_detalle_cupex_requisito = "+codUsu.trim());
			}else if(tipoChar.equals("d")){
				rs = stmt.executeQuery("select d.observacion from tb_documento_usuario d where d.cod_documento = '"+codUsu+"'");
			}else if(tipoChar.equals("a")){
				rs = stmt.executeQuery("select d.documento from tb_documento_usuario d where d.cod_documento = '"+codUsu+"'");
			}
			
			
			if (rs.next()) {
				if(tipoChar.equals("a")){
					archivo = rs.getBytes(1);
					archivo = descomprimirZipBD(archivo, codAdj);
				}else if(tipoChar.equals("d")){
					try {
						Document pdfDocument = new Document();
				        Reader htmlreader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream (rs.getBytes(1))));
				        ByteArrayOutputStream baos = new ByteArrayOutputStream();
				        PdfWriter.getInstance(pdfDocument, baos);
				        pdfDocument.open();
				        StyleSheet styles = new StyleSheet();
				        styles.loadTagStyle("body", "font", "Bitstream Vera Sans");
				        ArrayList arrayElementList = HTMLWorker.parseToList(htmlreader, styles);
				        for (int i = 0; i < arrayElementList.size(); ++i) {
				            Element e = (Element) arrayElementList.get(i);
				            pdfDocument.add(e);
				        }
				        pdfDocument.close();
						archivo = baos.toByteArray();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				else{
					System.out.println("ENTRE A OTROS");
					archivo = rs.getBytes(1);
				}
				
			} else {
				response.setContentType("text/html");
				out.println("<html><head><title>Archivo no disponible</title></head>");
				out.println("<body><h4><font color='red'>No se encontro el pdf especifico</font></h4></body></html>");
				return;
			}
			response.setContentType("application/pdf");
			InputStream in = new ByteArrayInputStream(archivo);
			int length;
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			while ((length = in.read(buffer)) != -1) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.flush();
		} catch (Exception e) {
			response.setContentType("text/html");
			out.println("<html><head><title>Archivo no disponible</title></head>");
			out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() + "</font></h4></body></html>");
			return;
		} finally {
			try {
				rs.close();
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
		
	final int BUFFER = 2048;
	private byte[] descomprimirZipBD(byte[] archivo, String buscar) {
		ByteArrayOutputStream fos = null;
		try {
			ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream (archivo));
	         ZipEntry entry;
	         while((entry = zis.getNextEntry()) != null) {
	        	 if(buscar.equals(entry.getName().substring(0, entry.getName().indexOf(".")))){
	        		int count;
	 	            byte data[] = new byte[BUFFER];
	 	            fos = new ByteArrayOutputStream();
	 	            while ((count = zis.read(data, 0, BUFFER)) != -1) {
	 	            	fos.write(data, 0, count);
	 	            }
	 	            fos.flush();
	 	            fos.close();
	        	 } 
	         }
	         zis.close();
	         
	      } catch(Exception e) {
	         e.printStackTrace();
	      }
		return fos.toByteArray();
	}
}
